package me.znext.learn.android.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.HashMap;

public class NoteDAO {
  private SQLiteDatabase db;// 创建SQLiteDatabase对象

  public NoteDAO(Context context) {
    DBHelper helper = new DBHelper(context);
    db = helper.getWritableDatabase();
    db.execSQL(
      "CREATE TABLE IF NOT EXISTS note (" +
        "nid INTEGER PRIMARY KEY," +
        "text text," +
        "time TimeStamp NOT NULL DEFAULT (datetime('now','localtime')))"
    );
  }

  public long add(String text) {
    ContentValues values = new ContentValues();
    values.put("text", text);
    return db.insert("note", null, values);
  }

  public ArrayList<HashMap<String, java.io.Serializable>> getAllNote() {
    Cursor cursor = db.rawQuery("SELECT * FROM note ORDER BY time DESC",new String[]{});
    ArrayList<HashMap<String, java.io.Serializable>> notes = new ArrayList<HashMap<String, java.io.Serializable>>();
    while (cursor.moveToNext()) {
      Integer nid = cursor.getInt(cursor.getColumnIndex("nid"));
      String text = cursor.getString(cursor.getColumnIndex("text"));
      String time = cursor.getString(cursor.getColumnIndex("time"));
      HashMap<String, java.io.Serializable> note = new HashMap<String, java.io.Serializable>();
      note.put("nid", nid);
      note.put("text", text);
      note.put("time", time);
      notes.add(note);
    }
    return notes;
  }
}
